package com.lx.wxpush.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lx.wxpush.utils.CaiHongPiUtils;
import com.lx.wxpush.utils.CalendarUtil;
import com.lx.wxpush.utils.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Api(tags = "微信推送接口")
@RestController
@RequestMapping("/wx")
public class WxController {

    @Value("${wx.config.appId}")
    private String appId;
    @Value("${wx.config.appSecret}")
    private String appSecret;
    @Value("${wx.config.templateId}")
    private String templateId;
    @Value("${wx.config.openid}")
    private String openid;
    @Value("${message.config.togetherDate}")
    private String togetherDate;
    @Value("${message.config.birthday.herBirthDay}")
    private String herBirthDay;
    @Value("${message.config.birthday.hisBirthDay}")
    private String hisBirthDay;
    @Value("${weather.config.url}")
    private String weatherUrl;
    @Value("${caihongpi.config.key}")
    private String key;
    private String message;
    private String accessToken = "";
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     *
     * 每天早上8：00执行推送
     *
     * @return
     */
    @Scheduled(cron = "0 0 8 ? * *")
    @ApiOperation("早安心语")
    @GetMapping("/getAccessToken")
    public String getAccessToken() throws Exception {
        Map paramMap = new HashMap<>();
        paramMap.put("grant_type", "client_credential");
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        String sendGet = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", paramMap);
        // 解析相应内容（转换成json对象）
        JSONObject jsonObject1 = JSONObject.parseObject(sendGet);
        logger.info("微信token响应结果=" + jsonObject1);
        //拿到accesstoken
        accessToken = (String) jsonObject1.get("access_token");
        return sendWeChatMsg(accessToken);
    }


    @Scheduled(cron = "59 59 23 ? * *")
    @ApiOperation("晚安心语")
    @GetMapping("/sendWanan")
    public String sendWanan() {
        Map paramMap = new HashMap<>();
        paramMap.put("grant_type", " ");
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        String sendGet = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", paramMap);
        // 解析相应内容（转换成json对象）
        JSONObject jsonObject1 = JSONObject.parseObject(sendGet);
        logger.info("微信token响应结果=" + jsonObject1);
        //拿到accesstoken
        accessToken = (String) jsonObject1.get("access_token");
        return sendWanAnMsg(accessToken);
    }


    /**
     * 发送微信消息
     *
     * @return
     */
    public String sendWeChatMsg(String accessToken) throws Exception {

        String[] openIds = openid.split(",");
        List<JSONObject> errorList = new ArrayList();
        for (String openId : openIds) {
            JSONObject templateMsg = new JSONObject(new LinkedHashMap<>());

            templateMsg.put("touser", openId);
            templateMsg.put("template_id", templateId);


            JSONObject first = new JSONObject();
            String date = DateUtil.format(new Date(), "yyyy-MM-dd");
            int week = DateUtil.weekOfMonth(new Date());
            String day = date + " " + week;
            first.put("value", day);
            first.put("color", "#EED016");

            String sendGet = HttpUtils.sendGet(weatherUrl, null);
            JSONObject weather = JSONObject.parseObject(sendGet);
            String address = "无法识别"; //城市
            String temHigh = "无法识别"; //最高温度
            String temLow = "无法识别"; //最低温度
            String weatherStatus = "";//天气状态
            if (!StringUtils.isEmpty(weather)) {
                temHigh = weather.getString("tem1") + "°";
                temLow = weather.getString("tem2") + "°";
                address = weather.getString("city");
                weatherStatus = weather.getString("wea");
            }

            JSONObject city = new JSONObject();
            city.put("value", address);
            city.put("color", "#60AEF2");

            String weatherInfo = weatherStatus + ", 温度:" + temLow + " ~ " + temHigh;

            JSONObject temperatures = new JSONObject();

            temperatures.put("value", weatherInfo);
            temperatures.put("color", "#44B549");

            JSONObject girlsDays = new JSONObject();
            long girlBirthDay = CalendarUtil.howManyDaysBeforeYourBirthday(herBirthDay);
            girlsDays.put("value", girlBirthDay);
            girlsDays.put("color", "#6EEDE2");

            JSONObject boysDays = new JSONObject();
            long boyBirthDay = CalendarUtil.howManyDaysBeforeYourBirthday(hisBirthDay);
            boysDays.put("value", boyBirthDay);
            boysDays.put("color", "#6EEDE2");


            JSONObject togetherDateObj = new JSONObject();
            long togetherDay = -1;
            try {
                togetherDay = DateUtil.betweenDay(DateUtil.parse(togetherDate), DateUtil.parse(date), false);
            } catch (Exception e) {
                logger.error("togetherDate获取失败" + e.getMessage());
            }
            togetherDateObj.put("value", togetherDay);
            togetherDateObj.put("color", "#FEABB5");

            JSONObject messageObj = new JSONObject();

            message = CaiHongPiUtils.getCaiHongPi(key);
            messageObj.put("value", message);
            messageObj.put("color", "#C79AD0");

            JSONObject remark = new JSONObject();
            remark.put("value", "❤❤❤❤今天也是爱你的一天哟❤❤❤❤");
            remark.put("color", "#FF0000");

            JSONObject tips = new JSONObject();
            tips.put("value", weather.getString("air_tips"));
            tips.put("color", "#66FFFF");

            JSONObject data = new JSONObject(new LinkedHashMap<>());
            data.put("first", first);
            data.put("remark", remark);
            data.put("tips", tips);
            data.put("city", city);
            data.put("temperature", temperatures);
            data.put("togetherDate", togetherDateObj);
            data.put("birthDate", girlsDays);
            data.put("birthDateHf", boysDays);
            data.put("message", messageObj);

            templateMsg.put("data", data);
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            System.out.println(templateMsg.toJSONString());
            String sendPost = HttpUtils.sendPost(url, templateMsg.toJSONString());
            JSONObject WeChatMsgResult = JSONObject.parseObject(sendPost);
            if (!"0".equals(WeChatMsgResult.getString("errcode"))) {
                JSONObject error = new JSONObject();
                error.put("openid", openId);
                error.put("errorMessage", WeChatMsgResult.getString("errmsg"));
                errorList.add(error);
            }
            logger.info("sendPost=" + sendPost);
        }
        JSONObject result = new JSONObject();
        result.put("result", "success");
        result.put("errorData", errorList);
        return result.toJSONString();
    }


    public String sendWanAnMsg(String accessToken) {

        String[] openIds = openid.split(",");
        List<JSONObject> errorList = new ArrayList();
        for (String openId : openIds) {
            JSONObject templateMsg = new JSONObject(new LinkedHashMap<>());

            templateMsg.put("touser", openId);
            templateMsg.put("template_id", "rZlQurCup_BUufNcZIBdL9JeZBjRATPC42nIJNhMGxY");

            JSONObject messageObj = new JSONObject();
            message = CaiHongPiUtils.getWanAn(key);
            messageObj.put("value", message);
            messageObj.put("color", "#C79AD0");

            JSONObject remark = new JSONObject();
            remark.put("value", "❤❤❤天蝎座明日运势❤❤❤");
            remark.put("color", "#FF0000");
            Map map = CaiHongPiUtils.getXingZuo(key);
            JSONObject luckyNum = new JSONObject();
            luckyNum.put("value", map.get("幸运数字"));
            luckyNum.put("color", "#000000");

            JSONObject work = new JSONObject();
            work.put("value", map.get("工作指数"));
            work.put("color", "#000000");

            JSONObject money = new JSONObject();
            money.put("value", map.get("财运指数"));
            money.put("color", "#000000");

            JSONObject love = new JSONObject();
            love.put("value", map.get("爱情指数"));
            love.put("color", "#000000");

            JSONObject luckyColor = new JSONObject();
            luckyColor.put("value", map.get("幸运颜色"));
            luckyColor.put("color", "#000000");

            JSONObject vipStar = new JSONObject();
            vipStar.put("value", map.get("贵人星座"));
            vipStar.put("color", "#000000");

            JSONObject data = new JSONObject(new LinkedHashMap<>());
            data.put("remark", remark);
            data.put("luckyNum", luckyNum);
            data.put("work", work);
            data.put("money", money);
            data.put("love", love);
            data.put("luckyColor", luckyColor);
            data.put("vipStar", vipStar);
            data.put("message", messageObj);

            templateMsg.put("data", data);
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            System.out.println(templateMsg.toJSONString());
            String sendPost = HttpUtils.sendPost(url, templateMsg.toJSONString());
            JSONObject WeChatMsgResult = JSONObject.parseObject(sendPost);
            if (!"0".equals(WeChatMsgResult.getString("errcode"))) {
                JSONObject error = new JSONObject();
                error.put("openid", openId);
                error.put("errorMessage", WeChatMsgResult.getString("errmsg"));
                errorList.add(error);
            }
            logger.info("sendPost=" + sendPost);
        }
        JSONObject result = new JSONObject();
        result.put("result", "success");
        result.put("errorData", errorList);
        return result.toJSONString();

    }
}
